#include "storage_system_cpp/StorageManager.h"
#include "storage_system_cpp/SystemCatalog.h"
#include <iostream>
#include <vector>
#include <memory>

int main() {
    std::cout << "=== 数据持久性测试 ===" << std::endl;

    // 创建第一个系统实例
    std::cout << "\n1. 创建第一个系统实例..." << std::endl;
    {
        auto storage_manager = std::make_shared<MiniDB::StorageManager>(50, MiniDB::ReplacementPolicy::LRU);
        auto system_catalog = std::make_shared<MiniDB::SystemCatalog>(storage_manager);

        // 创建表
        std::vector<MiniDB::ColumnInfo> columns = {
            {"id", MiniDB::DataType::INT, 4, false, true},
            {"name", MiniDB::DataType::VARCHAR, 50, true, false}
        };

        if (system_catalog->createTable("test_table", columns)) {
            std::cout << "✅ 表创建成功" << std::endl;
        }

        // 插入数据
        MiniDB::Record record1(1, "Test Data 1");
        if (storage_manager->insertRecord("test_table", record1)) {
            std::cout << "✅ 数据插入成功" << std::endl;
        }

        // 显示表信息
        auto table_names = storage_manager->getTableNames();
        std::cout << "表列表: ";
        for (const auto& name : table_names) {
            std::cout << name << " ";
        }
        std::cout << std::endl;

        // 强制保存
        system_catalog->saveCatalog();
        storage_manager->flushAll();

        std::cout << "✅ 第一个实例销毁，数据已保存" << std::endl;
    }

    // 创建第二个系统实例（模拟重启）
    std::cout << "\n2. 创建第二个系统实例（模拟重启）..." << std::endl;
    {
        auto storage_manager2 = std::make_shared<MiniDB::StorageManager>(50, MiniDB::ReplacementPolicy::LRU);
        auto system_catalog2 = std::make_shared<MiniDB::SystemCatalog>(storage_manager2);

        // 检查表是否恢复
        auto table_names2 = storage_manager2->getTableNames();
        std::cout << "恢复后的表列表: ";
        for (const auto& name : table_names2) {
            std::cout << name << " ";
        }
        std::cout << std::endl;

        if (!table_names2.empty()) {
            std::cout << "✅ 数据持久性测试通过！" << std::endl;

            // 尝试查询数据
            auto records = storage_manager2->getRecords("test_table");
            std::cout << "查询到 " << records.size() << " 条记录" << std::endl;
            for (const auto& record : records) {
                if (!record.is_deleted) {
                    std::cout << "  ID: " << record.id << ", Data: " << record.data << std::endl;
                }
            }
        } else {
            std::cout << "❌ 数据持久性测试失败！" << std::endl;
        }
    }

    std::cout << "\n=== 测试完成 ===" << std::endl;
    return 0;
}
